module Shape {
	export class CurveTest extends egret.DisplayObjectContainer{
		private _shape: egret.Shape;
		private _startShape: egret.Shape;
		private _control: egret.Shape;
		private _anchor: egret.Shape;

		/**
		 * 构造函数
		 */
		public constructor() {
			super();
			this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
		}

		/**
		 * 添加到舞台监听器
		 */
		private onAddToStage(event: egret.Event) {
			this._shape = new egret.Shape();
			this.addChild(this._shape);
			this.init();
		}

		/**
		 * 初始化
		 */
		private init(): void {
			this._startShape = this.initShape(140, 400, 0xffff00);
			this._control = this.initShape(340, 200, 0xff0000);
			this._anchor = this.initShape(480, 500, 0x000ff0);
			this.drawCurve();
		}

		/**
		 * 初始化（创建）圆
		 */
		private initShape(x: number, y: number, color: number): egret.Shape {
			var shape: egret.Shape = new egret.Shape();
			shape.graphics.beginFill(color);
			shape.graphics.drawCircle(0, 0, 20);
			shape.graphics.endFill();
			this.addChild(shape);
			shape.x = x;
			shape.y = y;
			shape.touchEnabled = true;
			shape.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBeginHandler, this);
			return shape;
		}

		/**
		 * 画Bezier曲线
		 */
		private drawCurve():void{
			this._shape.graphics.clear();
			this._shape.graphics.lineStyle(3,0xff0ff0);
			this._shape.graphics.moveTo(this._startShape.x,this._startShape.y);
			this._shape.graphics.curveTo(this._control.x,this._control.y,this._anchor.x,this._anchor.y);
			this._shape.graphics.lineStyle(3,0xffffff);
			this._shape.graphics.lineTo(this._control.x,this._control.y);
			this._shape.graphics.lineTo(this._startShape.x,this._startShape.y);
		}

		private drapShape: egret.Shape;
		private onBeginHandler(e: egret.TouchEvent): void {
			e.stopImmediatePropagation();

			this.drapShape = <egret.Shape>e.currentTarget;

			this.drapShape.touchEnabled = false;

			this.drapShape.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBeginHandler, this);
			this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMoveHandler, this);
			this.stage.addEventListener(egret.TouchEvent.TOUCH_END, this.onEndHandler, this);
		}

		private onMoveHandler(e: egret.TouchEvent): void {
			this.drapShape.x = e.stageX;
			this.drapShape.y = e.stageY;
			this.drawCurve();
		}

		private onEndHandler(e: egret.TouchEvent): void {
			this.drapShape.touchEnabled = true;;

			this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMoveHandler, this);
			this.stage.removeEventListener(egret.TouchEvent.TOUCH_END, this.onEndHandler, this);
			this.drapShape.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBeginHandler, this);
		}
	}
}